package pers.lls.im.core.util;

import lombok.extern.slf4j.Slf4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * @author lihuan
 * @version V1.0 创建时间：2019/8/02
 * Copyright 2019 by landray & STIC
 */
@Slf4j
public class IpUtil {

    private IpUtil() {
    }

    /***
     * 获取外网IP
     * @return
     */
    public static String internetIp() {
        try {
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress inetAddress;
            Enumeration<InetAddress> inetAddresses;
            while (networks.hasMoreElements()) {
                inetAddresses = networks.nextElement().getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();

                    boolean flag = inetAddress instanceof Inet4Address
                            && !inetAddress.isSiteLocalAddress()
                            && !inetAddress.isLoopbackAddress()
                            && inetAddress.getHostAddress().indexOf(':') == -1;
                    if (flag) {
                        return inetAddress.getHostAddress();
                    }
                }
            }

            return null;

        } catch (Exception e) {
            log.error(e.getMessage());

        }
        return "";
    }

    /**
     * 获取内网IP
     *
     * @return
     */
    public static String intranetIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }

    /**
     * 获取服务启动host
     *
     * @return
     */
    public static String getHost() {
        return internetIp() == null ? intranetIp() : internetIp();
    }



}
